/**
* https://github.com/Marfusios/websocket-client
*/
using System;
using Gtk;
using Gdk;
using UI = Gtk.Builder.ObjectAttribute;
using System.Threading.Tasks;
using System.Threading;
using Websocket.Client;

namespace face
{
    class MainWindow : Gtk.Window
    {
        //绑定ui控件
        [UI] private Label _label1 = null;
        [UI] private Button _button1 = null;
        [UI] private Image img= null;

        [UI] private TextView _logview = null;
        private int _counter;

        private WebsocketClient client;
        public MainWindow() : this(new Builder("MainWindow.glade")) { }

        private MainWindow(Builder builder) : base(builder.GetRawOwnedObject("MainWindow"))
        {
            builder.Autoconnect(this);
            DeleteEvent += Window_DeleteEvent;
            _button1.Clicked += Button1_Clicked;
            // byte[] img_ = Convert.FromBase64String();
            // img.Pixbuf = new Pixbuf(img_);
            _logview.Buffer.Text ="运行日志:";

            var exitEvent = new ManualResetEvent(false);
            var url = new Uri(FaceProxy.wsHost);
            // var url = new Uri("ws://localhost:11234");
            client = new WebsocketClient(url);
            client.ReconnectTimeout = TimeSpan.FromSeconds(30); // 通道空闲，重联间隔时间。
            client.ErrorReconnectTimeout = TimeSpan.FromSeconds(2);// 服务端丢失重连间隔
            client.ReconnectionHappened.Subscribe(info =>
            Console.WriteLine("Reconnection happened"));
            client.DisconnectionHappened.Subscribe(InfoBar => {
                Console.WriteLine("disconnect");
                });
            var utcNow = DateTime.UtcNow;
            var lastTime = utcNow - new DateTime(1970, 1, 1, 0, 0, 0);
            client.MessageReceived.Subscribe(msg =>
            {
                // string json = @"{""key1"":""value1"",""key2"":{"""":""""}}";
                var tmp = Json.Net.JsonNet.Deserialize<dynamic>(msg.Text);
                if (tmp.method == "face.updateUI")
                {
                    var utcNow = DateTime.UtcNow;
                    var timeSpan = utcNow - new DateTime(1970, 1, 1, 0, 0, 0);
                    if(lastTime.TotalMilliseconds + 80 > timeSpan.TotalMilliseconds){
                       return; 
                    }
                    lastTime = timeSpan;
                    byte[] img_ = Convert.FromBase64String(tmp.payload.image);
                    //gtk线程执行更新
                    Gtk.Application.Invoke(delegate
                    {
                        var pixbuf = new Pixbuf(img_);
                        pixbuf = pixbuf.ScaleSimple(img.AllocatedWidth,img.AllocatedHeight , Gdk.InterpType.Nearest);
                        // pixbuf = pixbuf.ScaleSimple(img.WidthRequest,img.HeightRequest , Gdk.InterpType.Nearest);
                        img.Pixbuf = pixbuf;
                    });
                    // Console.WriteLine(timeSpan.TotalMilliseconds);
                }else{
                    Console.WriteLine(msg);

                    Gtk.Application.Invoke(delegate
                    {
                        _logview.Buffer.Text =msg.Text;
                    });
                }
            });
            client.IsReconnectionEnabled = true;
            client.Start();
            // Task.Run(() => client.Send("{ message }"));
            
        }


        private void Window_DeleteEvent(object sender, DeleteEventArgs a)
        {
            Application.Quit();
        }

        private void Button1_Clicked(object sender, EventArgs a)
        {
            _counter++;
            _label1.Text = "Hello World! This button has been clicked " + _counter + " time(s).";

            img.File ="/home/czj/图片/12258387012_646493486.jpg";
        }
    }
}
